
import { ChangeEvent } from 'react';
import { Input } from 'antd';
import './forms.scss';
import { useFormItemInit } from './hooks';
import { TextAreaProps } from 'antd/es/input';
import { FormItemBaseProps } from './interface';
import React from 'react';
import { useDrag } from './drop.hooks';
import { Utils } from '../../utils/utils';
import { Components } from '../..';

const { TextArea } = Input;


interface IProps extends FormItemBaseProps {
}
export default function MyTextarea(props: IProps) {
    const { formControl, className = '', style = {} } = props;
    const {
        value, setValue,
        readonly,
        outerClassName,
        layout,
        showError,
        placeholder,
        outerStyle,
        labelStyle,
        selectorStyle,
    } = useFormItemInit(formControl, className, style);

    const onTextareaChange = (e: ChangeEvent<HTMLTextAreaElement>) => {
        const val = e.target.value;
        let value: any = undefined;
        if (Utils.isString(val)) {
            value = val.replace(/^[\n|\r|\t]+/g, '');
        } else {
            value = val;
        }
        setValue(value);
        formControl.setValue(value);
    };

    const textareaProps: TextAreaProps = {
        placeholder: (placeholder || '请输入'),
        value: value,
        className: 'textarea',
        rows: 3,
        autoSize: { minRows: 3, maxRows: 8 },
        maxLength: undefined,
        onChange: onTextareaChange,
        disabled: readonly,
        onPressEnter: (e) => {
            e.stopPropagation();
            if (Utils.isFunction(formControl.onPressEnter)) {
                formControl.onPressEnter!(e);
            }
            return
        },
        status: showError ? 'error' : undefined,
        styles: { 'textarea': selectorStyle },
    };

    /** 拖拽排序 */
    const dropRef = React.useRef<HTMLDivElement>(null);
    useDrag({ dropRef, formControl });

    /** 显示只读 */
    const renderReadonly = () => {
        let newValue =  '';
        if(Utils.isNotEmpty(value)){
            newValue = (value + '').replace(/\n/g, '<br/>');
        }
        return <div dangerouslySetInnerHTML={{ __html: newValue }}></div>;
    }

    return (
        <div component-name='form-item' className={outerClassName} style={outerStyle} ref={dropRef}>
            <div className={`field ${layout}`}>
                <Components.forms.FormLabel formControl={formControl} style={labelStyle} />
                <div className='control'>
                    <div className="value">
                        {
                            readonly ? <div className='textarea-readonly'>{renderReadonly()}</div> : <TextArea {...textareaProps} />
                        }
                    </div>
                </div>
            </div>
        </div>
    )
}
